﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Data;

/// <summary>
///DataTableToJson 的摘要说明
/// </summary>
public static class DataTableToJson
{

    /// <summary>
    /// 把DataTable 转换为json格式数据，以方便JavaScript接受
    /// </summary>
    /// <param name="dt">datatable 对象</param>
    /// <returns>string</returns>
    public static string ToJson(this DataTable dt)
    {
        if (dt != null)
        {
            StringBuilder html = new StringBuilder();
            html.Append("[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                html.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {


                    html.Append("\"" + dt.Columns[j].ColumnName + "\"");
                    html.Append(":");
                    html.Append("\"" + string2Json(dt.Rows[i][j].ToString()) + "\"");
                    html.Append(",");
                }

                html.Remove(html.Length - 1, 1);
                html.Append("},");

            }
            if (html.Length > 1)
            {
                html.Remove(html.Length - 1, 1);
            }
            html.Append("]");

            return html.ToString();
        }
        else
        {
            return "";
        }
    }

    /// <summary>
    /// 把字符串转化为json对象
    /// </summary>
    /// <param name="s">字符串</param>
    /// <returns>string</returns>
    private static string string2Json(string s)
    {
        StringBuilder sb = new StringBuilder(s.Length + 20);
        //字符串的char数组
        char[] charArray = s.ToCharArray();
        for (int i = 0; i < charArray.Length; i++)
        {
            char c = charArray[i];
            switch (c)
            {
                case '\"':
                    sb.Append("\\\"");
                    break;
                case '\\':
                    sb.Append("\\\\");
                    break;
                case '/':
                    sb.Append("\\/");
                    break;
                case '\b':
                    sb.Append("\\b");
                    break;
                case '\f':
                    sb.Append("\\f");
                    break;
                case '\n':
                    sb.Append("\\n");
                    break;
                case '\r':
                    sb.Append("\\r");
                    break;
                case '\t':
                    sb.Append("\\t");
                    break;
                default:
                    sb.Append(c);
                    break;
            }
        }

        return sb.ToString();
    }


}
